import { getRuleInfo, saveRuleInfo } from "@/services/patient/integralApi";
import { isExits, showMsg } from "@/utils/utils";
import ProForm, { ProFormDigit, ProFormText } from "@ant-design/pro-form";
import { Alert, Card, Form, FormInstance, Spin } from "antd";
import { useEffect, useRef, useState } from "react";

const RulesTab = () => {

  const [loading, setLoading] = useState<boolean>(false);
  const formRef = useRef<FormInstance>();

  const onFinish = async (values: PATIENT.RuleInfo) => {
    try {
      setLoading(true);
      await saveRuleInfo({ ...values });
      showMsg('保存成功', 'success');
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setLoading(true);
    getRuleInfo().then(res => {
      formRef.current?.setFieldsValue(res);
    }).catch(error => {
      showMsg(error?.data?.errmsg);
    }).finally(() => setLoading(false));
  }, []);

  return (
    <Spin spinning={loading}>
      <Card bordered={false}>
        <ProForm<PATIENT.RuleInfo>
          layout="horizontal"
          formRef={formRef}
          style={{ width: 560, marginLeft: '20%' }}
          submitter={{ searchConfig: { submitText: '保 存' }, render: (_, [, submitBtn]) => isExits('900901015') ? [submitBtn] : [] }}
          requiredMark={false}
          onFinish={onFinish}
        >
          <ProForm.Group title="积分兑换规则" spaceProps={{ style: { columnGap: 8 } }}>
            <ProFormDigit
              name="sett_price" label="每消费" colon={false} width={200}
              rules={[{ required: true, message: '请输入消费金额' }]}
            />
            <ProFormDigit
              name="integral" label="元，得" colon={false} width={200}
              addonAfter={<span style={{ whiteSpace: 'nowrap' }}>积分</span>}
              rules={[{ required: true, message: '请输入获得积分' }]}
            />
          </ProForm.Group>
          <ProForm.Group title="积分有效期">
            <ProFormDigit
              name="term_day" label="有效期" colon={false} width={200}
              addonAfter={<span>天</span>} rules={[{ required: true }]}
            />
          </ProForm.Group>
          <Form.Item wrapperCol={{ span: 13 }}>
            <Alert type="warning" message="用户积分超过有效期，将自动失效扣除" showIcon />
          </Form.Item>
          <ProFormText name="rule_id" hidden readonly />
        </ProForm>
      </Card>
    </Spin>
  );
};

export default RulesTab;
